import React from 'react'
import { Menu } from 'antd'
import store from '@/store'
import { openPage } from '@/utils/tools'
import { IFArticle } from '@/store/reducer'
import { getArticleById } from '@/apiList/api'
import { MenuInfo } from 'rc-menu/lib/interface'
const { SubMenu, Item } = Menu

type P = {}

type S = {
  articleList: IFArticle[]
  current: string
}

export default class SidebarMenu extends React.Component<P, S> {
  constructor(props: P) {
    super(props)
    this.state = {
      articleList: store.getState().articleList,
      current: ''
    }
    store.subscribe(this.storeChange)
  }
  storeChange = () => {
    if (this.state.articleList.length) return
    this.setState({
      articleList: store.getState().articleList
    })
  }
  handleClick = (e: MenuInfo) => {
    const id = e.key
    this.setState({ current: id })
    getArticleById({ id }).then((e: IFArticle) => {
      if (e.fileName.endsWith('.md')) {
        window.open(`/parseMarked/parseMarked.html?filePath=${e.filePath}`)
      } else {
        openPage(e.filePath)
      }
    })
  }
  render() {
    const { current, articleList } = this.state
    const renderList = (list: IFArticle[]): React.ReactElement[] => {
      return list.map((item) => {
        if (item.children) {
          return (
            <SubMenu key={item.id} title={item.fileName}>
              {renderList(item.children)}
            </SubMenu>
          )
        } else {
          return <Item key={item.id}>{item.fileName}</Item>
        }
      })
    }
    return (
      <div className="pr-30" style={{ position: 'sticky', top: '80px' }}>
        <Menu
          onClick={this.handleClick}
          selectedKeys={[current]}
          mode="vertical"
        >
          {renderList(articleList)}
        </Menu>
      </div>
    )
  }
}
